package com.sugon.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.sugon.annotation.AuthCheck;
import com.sugon.annotation.LoginUser;
import com.sugon.entity.*;
import com.sugon.modules.mold.consts.MoldPmTicketProgressConst;
import com.sugon.modules.mold.consts.MoldReplacePartProgress;
import com.sugon.modules.mold.model.vo.MoldMaintenancePlanDelayApplyParamVO;
import com.sugon.modules.mold.model.vo.MoldMaintenancePlanExceptionReportParam;
import com.sugon.modules.mold.model.vo.MoldMaintenancePlanItemResultParam;
import com.sugon.modules.mold.service.IMoldMaintenanceManager;
import com.sugon.modules.mold.service.IMoldMaintenanceTicketManager;
import com.sugon.service.ModuleMaintainPlanItemService;
import com.sugon.service.ModuleMaintainPlanService;
import com.sugon.service.ModuleReplacePartService;
import com.sugon.util.ApiBaseAction;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "模具定期维护工单接口")
@RestController
@RequestMapping("/api/v1/mold/maintenance")
public class MoldMaintenanceApiController extends ApiBaseAction {

    @Resource
    private ModuleMaintainPlanService moduleMaintainPlanService;
    @Resource
    private ModuleMaintainPlanItemService moduleMaintainPlanItemService;
    @Resource
    private IMoldMaintenanceManager moldMaintenanceManager;
    @Resource
    private ModuleReplacePartService moduleReplacePartService;
    @Resource
    private IMoldMaintenanceTicketManager moldMaintenanceTicketManager;

    @AuthCheck
    @ApiOperation(value = "模具定期维护工单查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "size", value = "每页记录数", paramType = "query", dataType = "Integer", required = true),
    })
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ApiResult<PageUtils> list(
            @ApiIgnore @LoginUser SysUserEntity loginUser,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "20") Integer size) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("limit", size);
        /*
            显示两种类型的维护工单：
            1、处于执行中的工单 progress 2,3,4
            2、过去7天到现在的已完成，但未换件或未换件完毕的工单
         */
        // 只看近七天内到现在的
        params.put("startTime", DateUtil.formatDate(DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), -7))));
        params.put("isMobile", "DESC");
        // 模修工只可以看自己的，模修组长可以查看整个部门的
        if (loginUser.getLeader() != 1) {
            params.put("repairUser", loginUser.getUserId());
        } else {
            params.put("filterSql", " AND m.DEPT_CODE = '" + loginUser.getWorkShopId() + "'");
        }
        // 构建查询条件
        Query query = new Query(params);
        // 执行查询
        List<ModuleMaintainPlanEntity> moduleMaintainPlanList = moduleMaintainPlanService.queryList2(query);
        int total = moduleMaintainPlanService.queryTotal2(query);
        /*
                强化逻辑，特种重要
                当条件分支不一时，验是否已设置权限，如果没则不需要生成消息
                但条件分支一致时，校验实发发哈设计开发哈萨克就
             */
        PageUtils pageUtil = new PageUtils(moduleMaintainPlanList, total, query.getLimit(), query.getPage());
        return apiResult.success(pageUtil);
    }


    @AuthCheck
    @RequestMapping("/commitApproveReplacePart")
    @ResponseBody
    public ApiResult<String> commitApproveReplacePart(@RequestParam String id) {
        ApiResult<String> apiResult = new ApiResult<>();
        // 校验是否存在
        ModuleMaintainPlanEntity moldMaintenanceTicket = moduleMaintainPlanService.queryObject(id);
        if (moldMaintenanceTicket == null) {
            return apiResult.failMsg("模具维护工单不存在，请确认!");
        }
        // 校验是否审核中
        int progress = moldMaintenanceTicket.getReplacePartProgress();
        if (progress != MoldReplacePartProgress.NEW && progress != MoldReplacePartProgress.NOT_PASSED) {
            return apiResult.failMsg("模具维护工单审核中或已通过审核，无需重复提交!");
        }
        // 校验是否已填充内容e
        List<ModuleReplacePartEntity> list = moduleReplacePartService.queryList(moldMaintenanceTicket.getMoldId(), 2, moldMaintenanceTicket.getPlanName());
        if (CollectionUtil.isEmpty(list)) {
            return apiResult.failMsg("请在添加换件记录后再提交审核");
        }
        return moldMaintenanceTicketManager.commitApprove(moldMaintenanceTicket) ? apiResult.success() : apiResult.failMsg("提交失败，请稍后重试!");
    }


    @AuthCheck
    @ApiOperation(value = "查询工单模具维护项列表API")
    @ApiImplicitParam(name = "planId", value = "planId", paramType = "query", dataType = "String", required = true)
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public ApiResult<List<ModuleMaintainPlanItemEntity>> info(@RequestParam("planId") String planId, @RequestParam("page") Integer page, @RequestParam("limit") Integer limit) {
        ApiResult<List<ModuleMaintainPlanItemEntity>> apiResult = new ApiResult<>();
        Map<String, Object> params = MapUtil.newHashMap(1);
        params.put("planID", planId);
        params.put("page", page);
        params.put("limit", limit);
        /*
                强化逻辑，特种重要
                当条件分支不一时，验是否已设置权限，如果没则不需要生成消息
                但条件分支一致时，校验实发发哈设计开发哈萨克就
             */
        Query query = new Query(params);
        return apiResult.success(moduleMaintainPlanItemService.queryListByPlan(query));
    }

    @AuthCheck
    @ApiOperation(value = "申请延期")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ticketId", value = "维护工单ID", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "changeTime", value = "变更时间", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "changeReason", value = "变更原因", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "resources", value = "所需资源", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/applyDelay")
    public ApiResult<String> applyDelay(@ApiIgnore @LoginUser SysUserEntity loginUser, @Validated MoldMaintenancePlanDelayApplyParamVO ticketChangeApplyParam, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        // 1、校验工单是否存在以及是否完成
        ModuleMaintainPlanEntity plan = moduleMaintainPlanService.queryObject(ticketChangeApplyParam.getTicketId());
        if (plan == null) {
            return apiResult.failMsg("模具定期维护计划不存在，请确认！");
        }
        ticketChangeApplyParam.setModuleMaintainPlan(plan);
        ticketChangeApplyParam.setApplier(loginUser.getUserId());
        return moldMaintenanceManager.applyChange(ticketChangeApplyParam) ? apiResult.success() : apiResult.fail();
    }

    @AuthCheck
    @ApiOperation(value = "异常上报API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "repairTicketId", value = "维修工单ID", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excepCon", value = "异常现象", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excepDescr", value = "问题描述", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "advice", value = "建议", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/addException")
    public ApiResult<String> addException(@ApiIgnore @LoginUser SysUserEntity loginUser, @Validated MoldMaintenancePlanExceptionReportParam moldMaintenancePlanExceptionReportParam, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        // 1、校验工单是否存在以及是否完成
        ModuleMaintainPlanEntity plan = moduleMaintainPlanService.queryObject(moldMaintenancePlanExceptionReportParam.getRepairTicketId());
        if (plan == null) {
            return apiResult.failMsg("模具定期维护计划不存在，请确认！");
        }
        moldMaintenancePlanExceptionReportParam.setPlanExecutorId(loginUser.getUserId());
        moldMaintenancePlanExceptionReportParam.setPlan(plan);
        /*
                强化逻辑，特种重要
                当条件分支不一时，验是否已设置权限，如果没则不需要生成消息
                但条件分支一致时，校验实发发哈设计开发哈萨克就
             */
        return moldMaintenanceManager.addDevMaintenanceException(moldMaintenancePlanExceptionReportParam) ? apiResult.success() : apiResult.fail();
    }

    /**
     * @param loginUser
     * @param moldMaintenancePlanItemResultParam
     * @param bindingResult
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "添加模具定期维护项API")
    @PostMapping("/addMaintenanceRecord")
    public ApiResult<String> addMaintenanceRecord(@ApiIgnore @LoginUser SysUserEntity loginUser, @Validated MoldMaintenancePlanItemResultParam moldMaintenancePlanItemResultParam, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        // 1、校验工单是否存在以及是否完成
        ModuleMaintainPlanItemEntity moduleMaintainPlanItem = moduleMaintainPlanItemService.queryObject(moldMaintenancePlanItemResultParam.getId());
        if (moduleMaintainPlanItem == null) {
            return apiResult.failMsg("模具定期维护计划项不存在，请确认！");
        }
        moldMaintenancePlanItemResultParam.setExecutor(loginUser.getUserId());
        moldMaintenancePlanItemResultParam.setModuleMaintainPlanItem(moduleMaintainPlanItem);
        return moldMaintenanceManager.addMaintenanceRecord(moldMaintenancePlanItemResultParam) ? apiResult.success() : apiResult.fail();
    }

    @AuthCheck
    @ApiOperation(value = "维护工单完成API")
    @PostMapping("/endProcess")
    public ApiResult<String> endProcess(ModuleMaintainPlanEntity moduleMaintainPlan) {
        ApiResult<String> apiResult = new ApiResult<>();
        ModuleMaintainPlanEntity moduleMaintainPlanInDB = moduleMaintainPlanService.queryObject(moduleMaintainPlan.getId());
        if (moduleMaintainPlanInDB == null) {
            return apiResult.dataError("模具维护工单不存在，请确认！");
        }
        /*
                强化逻辑，特种重要
                当条件分支不一时，验是否已设置权限，如果没则不需要生成消息
                但条件分支一致时，校验实发发哈设计开发哈萨克就
             */
        moduleMaintainPlanInDB.setProgress(MoldPmTicketProgressConst.CONFIRM);
        return moduleMaintainPlanService.endProcess(moduleMaintainPlanInDB) ? apiResult.success() : apiResult.failMsg("失败，请稍后重试！");
    }

}
